package com.tanhua.server.service;

import com.tanhua.autoconfig.template.HuanXinTemplate;
import com.tanhua.autoconfig.template.SmsTemplate;
import com.tanhua.commons.utils.Constants;
import com.tanhua.commons.utils.JwtUtils;
import com.tanhua.dubbo.api.UserApi;
import com.tanhua.model.domain.User;
import com.tanhua.model.vo.ErrorResult;
import com.tanhua.server.exeception.BusinessException;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.time.Duration;
import java.util.HashMap;
import java.util.Map;

/**
 * @author SunSun
 * @date 2021/10/21
 */
@Service
public class UserService {

    @Autowired
    private SmsTemplate smsTemplate;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @DubboReference
    private UserApi userApi;

    @Autowired
    private HuanXinTemplate huanXinTemplate;

    @Autowired
    private UserFreezeService userFreezeService;

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Autowired
    private MqMessageService mqMessageService;

    public void sendMsg(String phone) {
        User user = userApi.findByMobile(phone);
        if (user != null) {
            userFreezeService.checkUserStatus("1", user.getId());
        }

//        String code = RandomStringUtils.randomNumeric(6);
//
//        smsTemplate.sendSms(phone,code);
        String code = "123456";

        redisTemplate.opsForValue().set("CHECK_CODE" + phone, code, Duration.ofMinutes(5));
    }

    public Map loginVerification(String phone, String code) {

        String rediscode = redisTemplate.opsForValue().get("CHECK_CODE" + phone);

        if (rediscode.isEmpty() || !rediscode.equals(code)) {
            throw new BusinessException(ErrorResult.loginError());
        }

        redisTemplate.delete("CHECK_CODE" + phone);

        User user = userApi.findByMobile(phone);

        boolean isNew = false;

        String type = "0101";
        if (user == null) {
            type = "0102";
            user = new User();
            user.setMobile(phone);
            user.setPassword(DigestUtils.md5Hex("123456"));
            Long userId = userApi.save(user);
            user.setId(userId);
            isNew = true;

            String hxUser = "hx" + user.getId();
            Boolean user1 = huanXinTemplate.createUser(hxUser, Constants.INIT_PASSWORD);
            if (user1) {
                user.setHxUser(hxUser);
                user.setHxPassword(Constants.INIT_PASSWORD);
                userApi.update(user);
            }

        }

//        try {
//            Map map=new HashMap();
//            map.put("id",user.getId());
//            map.put("type",type);
//            map.put("logTime",new SimpleDateFormat("yyyy-MM-dd").format(new Date()));
//            String message = JSON.toJSONString(map);
//            rabbitTemplate.convertAndSend("tanhua.log.exchange",
//                    "log.user",message);
//        }catch (Exception e){
//            e.printStackTrace();
//        }

        mqMessageService.sendLogMessage(user.getId(),type,"user",null);

        Map tokenMap = new HashMap();
        tokenMap.put("id", user.getId());
        tokenMap.put("mobile", phone);
//        long now = System.currentTimeMillis();
//        String token = Jwts.builder()
//                .signWith(SignatureAlgorithm.HS512, "itcast")
//                .setClaims(tokenMap)
//                .setExpiration(new Date(now + 300000))
//                .compact();

        String token = JwtUtils.getToken(tokenMap);

        System.out.println(token);
        Map retMap = new HashMap();
        retMap.put("token", token);
        retMap.put("isNew", isNew);

        return retMap;
    }
}
